package com.miner;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;

import com.miner.updatedemo.R;
import com.miner.updatedemo.service.DownloadAPKService;

import java.util.Set;

public class MainActivity extends AppCompatActivity {

    public static final String UPDATE_URL_EXTRA = "update_url_extra";
    public static final String START_DOWNLOAD_EXTRA = "start_download";
    private final String URL_STR = "http://www.zhaoshangdai.com/file/android.apk";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (downloadThreadAvailed(DownloadAPKService.DOWNLOAD_THREAD_NAME)) {
            Intent intent = new Intent(this, UpdateActivity.class);
            intent.putExtra(START_DOWNLOAD_EXTRA, true);
            intent.putExtra(UPDATE_URL_EXTRA, URL_STR);
            startActivity(intent);
            finish();
        } else {
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("检测到新版本，是否现在更新应用?")
                    .setCancelable(false)
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            finish();
                        }
                    })
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Intent it = new Intent(MainActivity.this, UpdateActivity.class);
                            it.putExtra(UPDATE_URL_EXTRA, URL_STR);
                            startActivity(it);
                            finish();
                        }
                    })
                    .show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private boolean downloadThreadAvailed(String threadName) {
        Set<Thread> threads = Thread.getAllStackTraces().keySet();
        for (Thread thread : threads) {
            if (TextUtils.equals(thread.getName(), threadName))
                return true;
        }
        return false;
    }
}
